use rdev::{listen, simulate, Button, Event, EventType, Key, SimulateError};
use std::{thread, time};

fn main() {
    // This will block.
    let mut cur_mouse_pos = (0.0, 0.0);
    let mut pos_mouse_: Vec<(f64, f64)> = Vec::new();
    let mut isrun = false;
    let callback = move |event: Event| {
        match event.event_type {
            EventType::KeyPress(Key::F8) => {
                println!("pos is {:?}",pos_mouse_);
                isrun = true;
                for (x, y) in pos_mouse_.iter() {
                    send(&EventType::MouseMove { x: *x, y: *y });
                    send(&EventType::ButtonPress(Button::Left));
                    send(&EventType::ButtonRelease(Button::Left));
                }
                isrun = false;
            }
            _ => {}
        };
        if isrun {
            return;
        }
        match event.event_type {
            EventType::ButtonPress(Button::Left) => {
                pos_mouse_.push(cur_mouse_pos);
            }
            EventType::MouseMove { x, y } => {
                cur_mouse_pos = ((x / 1.5).floor(), (y / 1.5).floor());
            }
            _ => {}
        };
    };

    if let Err(error) = listen(callback) {
        println!("Error: {:?}", error)
    }
}

fn send(event_type: &EventType) {
    let delay = time::Duration::from_millis(100);
    match simulate(event_type) {
        Ok(()) => (),
        Err(SimulateError) => {
            println!("We could not send {:?}", event_type);
        }
    }
    // Let ths OS catchup (at least MacOS)
    thread::sleep(delay);
}
